<template>
  <div class="payroll-config-container">
    <!-- 社保配置卡片 -->
    <el-card class="config-card" shadow="never">
      <template #header>
        <span class="card-header">社保方案</span>
      </template>

      <el-form-item label="社保方案类型">
        <el-select v-model="housingFormData.schemeType" placeholder="请选择">
          <el-option label="
上海社保唯一标准" value="shanghai"></el-option>
          <el-option label="
北京社保唯一标准" value="beijing"></el-option>
          <el-option label="自定义方案" value="custom"></el-option>
        </el-select>
      </el-form-item>


      <div class="form-section">
        <el-form ref="socialForm" :model="socialFormData" label-width="0">
          <table class="form-table">
            <thead>
              <tr>
                <th>险种名称</th>
                <th>基数下限</th>
                <th>基数上限</th>
                <th>公司比例(%)</th>
                <th>公司固定金额(元)</th>
                <th>个人比例(%)</th>
                <th>个人固定金额(元)</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(item, index) in socialFormData" :key="index">
                <td>
                  <el-form-item>
                    <el-input v-model="item.categoryName" />
                  </el-form-item>
                </td>
                <td>
                  <el-form-item>
                    <el-input v-model.number="item.baseMin" type="number">
                      <template #append>元</template>
                    </el-input>
                  </el-form-item>
                </td>
                <td>
                  <el-form-item>
                    <el-input v-model.number="item.baseMax" type="number">
                      <template #append>元</template>
                    </el-input>
                  </el-form-item>
                </td>
                <td>
                  <el-form-item>
                    <el-input v-model.number="item.companyRatio" type="number" :precision="2">
                      <template #append>%</template>
                    </el-input>
                  </el-form-item>
                </td>
                <td>
                  <el-form-item>
                    <el-input v-model.number="item.companyFixedAmount" type="number">
                      <template #append>元</template>
                    </el-input>
                  </el-form-item>
                </td>
                <td>
                  <el-form-item>
                    <el-input v-model.number="item.personalRatio" type="number" :precision="2">
                      <template #append>%</template>
                    </el-input>
                  </el-form-item>
                </td>
                <td>
                  <el-form-item>
                    <el-input v-model.number="item.personalFixedAmount" type="number">
                      <template #append>元</template>
                    </el-input>
                  </el-form-item>
                </td>
                <td>
                  <el-button type="danger" icon="Delete" circle @click="removeSocialItem(index)" />
                </td>
              </tr>
            </tbody>
          </table>

          <div class="action-buttons">
            <el-button type="primary" icon="Plus" @click="addSocialItem">新增险种</el-button>
            <el-button type="warning" @click="resetSocialForm">重置</el-button>
          </div>
        </el-form>
      </div>
    </el-card>

    <!-- 公积金配置卡片 -->
    <el-card class="config-card" shadow="never" style="margin-top: 20px;">
      <template #header>
        <span class="card-header">公积金方案</span>
      </template>


      <el-form-item label="公积金方案类型">
        <el-select v-model="housingFormData.schemeType" placeholder="请选择">
          <el-option label="上海公积金8+8" value="shanghai"></el-option>
          <el-option label="北京公积金12%" value="beijing"></el-option>
          <el-option label="自定义方案" value="custom"></el-option>
        </el-select>
      </el-form-item>


      <div class="form-section">
        <el-form ref="housingForm" :model="housingFormData" label-width="0">
          <table class="form-table">
            <thead>
              <tr>
                <th>公积金类型</th>
                <th>基数下限</th>
                <th>基数上限</th>
                <th>公司比例(%)</th>
                <th>公司固定金额(元)</th>
                <th>个人比例(%)</th>
                <th>个人固定金额(元)</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(item, index) in housingFormData" :key="index">
                <td>
                  <el-form-item>
                    <el-input v-model="item.insuranceType" readonly />
                  </el-form-item>
                </td>
                <td>
                  <el-form-item>
                    <el-input v-model.number="item.baseMin" type="number">
                      <template #append>元</template>
                    </el-input>
                  </el-form-item>
                </td>
                <td>
                  <el-form-item>
                    <el-input v-model.number="item.baseMax" type="number">
                      <template #append>元</template>
                    </el-input>
                  </el-form-item>
                </td>
                <td>
                  <el-form-item>
                    <el-input v-model.number="item.companyRatio" type="number" :precision="2">
                      <template #append>%</template>
                    </el-input>
                  </el-form-item>
                </td>
                <td>
                  <el-form-item>
                    <el-input v-model.number="item.companyFixedAmount" type="number">
                      <template #append>元</template>
                    </el-input>
                  </el-form-item>
                </td>
                <td>
                  <el-form-item>
                    <el-input v-model.number="item.personalRatio" type="number" :precision="2">
                      <template #append>%</template>
                    </el-input>
                  </el-form-item>
                </td>
                <td>
                  <el-form-item>
                    <el-input v-model.number="item.personalFixedAmount" type="number">
                      <template #append>元</template>
                    </el-input>
                  </el-form-item>
                </td>
                <td>
                  <el-button type="danger" icon="Delete" circle @click="removeHousingItem(index)" />
                </td>
              </tr>
            </tbody>
          </table>

          <div class="action-buttons">
            <el-button type="primary" icon="Plus" @click="addHousingItem">新增项目</el-button>
            <el-button type="warning" @click="resetHousingForm">重置</el-button>
          </div>
        </el-form>
      </div>
    </el-card>

    <!-- 费用统计卡片 -->
    <el-card class="stats-card" shadow="never" style="margin-top: 20px;">
      <template #header>
        <span class="card-header">费用统计</span>
      </template>
      <div class="stats-container">
        <div class="stat-item">
          <div class="stat-label">个人缴费总计：</div>
          <div class="stat-value highlight">{{ totalPersonal | currency }}</div>
        </div>
        <div class="stat-item">
          <div class="stat-label">企业缴费总计：</div>
          <div class="stat-value highlight">{{ totalCompany | currency }}</div>
        </div>
        <div class="stat-item">
          <div class="stat-label">全部缴费合计：</div>
          <div class="stat-value highlight">{{ totalAll | currency }}</div>
        </div>
      </div>
    </el-card>

    <!-- 底部操作栏 -->
    <div class="action-bar">
      <el-button type="primary" @click="saveConfig">保存</el-button>
      <el-button @click="cancelEdit">取消</el-button>
    </div>
  </div>
</template>

<script setup>

import { ref, computed, onMounted,onUnmounted  } from 'vue';
import { ElMessage } from 'element-plus';
import axios from 'axios';


// 社保和公积金数据
const socialFormData = ref({
  items: []
});

const housingFormData = ref({
  schemeType: 'shanghai',
  items: []
});

// 费用统计
const totalPersonal = computed(() => {
  return calculateTotal(socialFormData.value.items, 'personal') +
    calculateTotal(housingFormData.value.items, 'personal');
});

const totalCompany = computed(() => {
  return calculateTotal(socialFormData.value.items, 'company') +
    calculateTotal(housingFormData.value.items, 'company');
});

const totalAll = computed(() => totalPersonal.value + totalCompany.value);

// 加载数据的函数
const loadData = async () => {
  // 从 localStorage 中获取 token
  const token = getToken(); 
  if (!token) {
    console.error('未获取到有效的 token');
    ElMessage.error('未获取到有效的 token，请重新登录');
    return;
  }
  try {
    const [socialResponse, housingResponse] = await Promise.all([
      axios.get('http://localhost:8080/detail/detail/list', {
        headers: {
          // 使用正确的 token 变量
          Authorization: `Bearer ${token}` 
        }
      }),
      axios.get('http://localhost:8080/detail/detail/list', {
        headers: {
          Authorization: `Bearer ${token}`
        }
      })
    ]);

    socialFormData.value.items = socialResponse.data || [];
    housingFormData.value.items = housingResponse.data || [];
  } catch (error) {
    console.error('加载数据失败:', error);
    ElMessage.error('加载配置数据失败，请重试');
    resetToDefaultData();
  }
};


let refreshInterval;
onMounted(() => {
  loadData();
  refreshInterval = setInterval(loadData, 10000);
});
onUnmounted(() => {
  // 组件卸载时清除定时器
  clearInterval(refreshInterval);
});

// 计算总费用
function calculateTotal(items, type) {
  return items.reduce((sum, item) => {
    const rate = type === 'company' ? item.companyRate : item.personalRate;
    const fixed = type === 'company' ? item.companyFixed : item.personalFixed;

    if (rate > 0) {
      // 这里简化计算，实际应根据业务逻辑调整
      return sum + (rate / 100 * (item.baseMax + item.baseMin) / 2);
    } else if (fixed > 0) {
      return sum + fixed * 2; // 假设上下限相同
    } else {
      return sum + ((item.baseMax + item.baseMin) / 2);
    }
  }, 0);
}

// 保存配置
const saveConfig = async () => {
  try {
    const requestData = {
      social: socialFormData.value.items,
      housing: housingFormData.value.items
    };

    await axios.post(`${API_BASE_URL}/save`, requestData);

    ElMessage.success('配置已保存！');
  } catch (error) {
    console.error('保存失败:', error);
    ElMessage.error('保存配置失败，请重试');
  }
};

// 新增/删除方法
const addSocialItem = () => {
  socialFormData.value.items.push({
    name: '',
    baseMin: 0,
    baseMax: 0,
    companyRate: 0,
    companyFixed: 0,
    personalRate: 0,
    personalFixed: 0
  });
};

const removeSocialItem = (index) => {
  socialFormData.value.items.splice(index, 1);
};

const addHousingItem = () => {
  housingFormData.value.items.push({
    type: 'housing',
    name: '',
    baseMin: 0,
    baseMax: 0,
    companyRate: 0,
    companyFixed: 0,
    personalRate: 0,
    personalFixed: 0
  });
};

const removeHousingItem = (index) => {
  housingFormData.value.items.splice(index, 1);
};

const resetSocialForm = () => {
  loadData().then(() => {
    // 重新加载社保数据
  });
};

const resetHousingForm = () => {
  // 对于公积金，我们可能需要区分方案类型
  // 这里简化处理，直接重置为默认数据
  resetToDefaultData();
};

</script>

<style scoped>
.payroll-config-container {
  padding: 20px;
}

.config-card {
  margin-bottom: 20px;
}

.card-header {
  font-size: 18px;
  font-weight: bold;
  color: #409EFF;
}

.form-section {
  padding: 20px;
}

.item-row {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.item-row :deep(.el-form-item) {
  margin-bottom: 0;
}

.item-row :deep(.el-form-item__content) {
  margin-left: 0 !important;
}

.action-buttons {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
}

.stats-card {
  flex: 1;
}

.stats-container {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.stat-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.stat-label {
  color: #606266;
}

.highlight {
  color: #409EFF;
  font-weight: bold;
}

.action-bar {
  display: flex;
  justify-content: space-between;
  padding: 15px;
  background-color: #f9fafc;
  border-top: 1px solid #e4e7ed;
}

.payroll-config-container {
  padding: 20px;
  max-width: 80%;
  /* 限制容器最大宽度为80% */
  margin: 0 auto;
  /* 水平居中 */
}

.config-card {
  margin-bottom: 20px;
}

.item-row {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  flex-wrap: nowrap;
  /* 禁止换行 */
}

/* 优化列布局 */
.el-col {
  flex: 0 0 auto;
  /* 禁止列元素缩放 */
}

/* 调整按钮栏布局 */
.action-buttons,
.action-bar {
  justify-content: flex-start;
  /* 按钮左对齐减少右侧空白 */
  gap: 10px;
  /* 增加按钮间距 */
}

/* 优化统计卡片布局 */
.stats-container {
  max-width: 100%;
  /* 确保统计卡片不超出容器 */
}

.form-table {
  width: 100%;
  border-collapse: collapse;
  margin-bottom: 20px;
}

.form-table th,
.form-table td {
  border: 1px solid #EBEEF5;
  padding: 10px;
  text-align: left;
}

.form-table th {
  background-color: #F5F7FA;
  font-weight: 500;
}

.form-table td {
  vertical-align: middle;
}

/* 表单元素在表格中的样式 */
.form-table .el-form-item {
  margin-bottom: 0;
}

.form-table .el-input,
.form-table .el-select {
  width: 100%;
}

/* 操作按钮样式 */
.form-table .el-button {
  padding: 5px;
}

/* 其他样式保持不变 */
.payroll-config-container {
  padding: 20px;
  max-width: 1200px;
  /* 限制最大宽度 */
  margin: 0 auto;
}

.config-card {
  margin-bottom: 20px;
}

.action-buttons,
.action-bar {
  display: flex;
  gap: 10px;
  margin-top: 20px;
}

.stats-container {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.stat-item {
  display: flex;
  justify-content: space-between;
  padding: 10px 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.stat-label {
  color: #606266;
}

.highlight {
  color: #409EFF;
  font-weight: bold;
}
</style>